import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { startTokenExpirationCheck, stopTokenExpirationCheck } from '@/utils/token'

export interface Permission {
    id: string
    name: string
    code: string
    type: string
    module: string
}

export interface Role {
    id: string
    name: string
    code: string
}

export interface UserInfo {
    id: number
    username: string
    name: string
    email: string
    avatar?: string
    role: string
    roles: Role[]
    permissions: Permission[]
}

export const useUserStore = defineStore('user', () => {
    const accessToken = ref<string>(localStorage.getItem('hospital-access-token') || '')
    const refreshToken = ref<string>(localStorage.getItem('hospital-refresh-token') || '')
    const userInfo = ref<UserInfo | null>(null)

    // 兼容旧的token字段
    const token = computed(() => accessToken.value)

    const setTokens = (newAccessToken: string, newRefreshToken: string) => {
        accessToken.value = newAccessToken
        refreshToken.value = newRefreshToken
        localStorage.setItem('hospital-access-token', newAccessToken)
        localStorage.setItem('hospital-refresh-token', newRefreshToken)

        // 启动token过期检查
        startTokenExpirationCheck()
    }

    const setToken = (newToken: string) => {
        // 兼容单token的旧方法
        accessToken.value = newToken
        localStorage.setItem('hospital-access-token', newToken)
    }

    const setUserInfo = (info: UserInfo) => {
        userInfo.value = info
    }

    const logout = () => {
        accessToken.value = ''
        refreshToken.value = ''
        userInfo.value = null
        localStorage.removeItem('hospital-access-token')
        localStorage.removeItem('hospital-refresh-token')
        // 清理旧的token存储
        localStorage.removeItem('hospital-admin-token')

        // 停止token过期检查
        stopTokenExpirationCheck()
    }

    // 权限检查方法
    const hasPermission = (permissionCode: string) => {
        if (!userInfo.value?.permissions) return false

        // 直接匹配权限编码
        const directMatch = userInfo.value.permissions.some(p => p.code === permissionCode)
        if (directMatch) {
            return true
        }

        // 如果没有直接匹配，检查是否有该模块下的任何操作权限
        // 例如：需要 'doctor' 权限时，检查是否有 'doctor:*' 权限
        const moduleMatch = userInfo.value.permissions.some(p =>
            p.code.startsWith(permissionCode + ':')
        )

        // 权限检查日志（可选择性开启调试）
        // console.log(`权限检查 ${permissionCode}: 直接匹配=${directMatch}, 模块匹配=${moduleMatch}`)

        return moduleMatch
    }

    // 角色检查方法
    const hasRole = (roleCode: string) => {
        if (!userInfo.value?.roles) return false
        return userInfo.value.roles.some(r => r.code === roleCode)
    }

    // 模块权限检查方法
    const hasModulePermission = (module: string) => {
        if (!userInfo.value?.permissions) return false
        return userInfo.value.permissions.some(p => p.module === module)
    }

    // 是否为超级管理员
    const isSuperAdmin = computed(() => {
        return hasRole('super_admin')
    })

    // 获取用户权限代码列表（兼容旧代码）
    const permissionCodes = computed(() => {
        return userInfo.value?.permissions.map(p => p.code) || []
    })

    return {
        token, // 兼容旧代码
        accessToken,
        refreshToken,
        userInfo,
        setToken, // 兼容旧代码
        setTokens,
        setUserInfo,
        logout,
        hasPermission,
        hasRole,
        hasModulePermission,
        isSuperAdmin,
        permissionCodes
    }
})